package cn.com.czpb.client.module.news.activity;

import android.content.Context;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import cn.com.czpb.client.R;
import cn.com.czpb.client.app.ToolBarActivityWhite;
import cn.com.czpb.client.custorm.TagCloudLayout;
import cn.com.czpb.client.model.news.HotSearchBean;
import cn.com.czpb.client.model.news.HotSearchEntity;
import cn.com.czpb.client.model.news.SearchHisBean;
import cn.com.czpb.client.module.news.adapter.SearchFragmentPagerAdapter;
import cn.com.czpb.client.module.news.adapter.TagBaseAdapter;
import cn.com.czpb.client.module.news.adapter.TagHistoryAdapter;
import cn.com.czpb.client.module.news.fragment.SearchNewsFragment;
import cn.com.czpb.client.module.news.fragment.SearchSubscribeFragment;
import cn.com.czpb.client.module.news.listener.RefreshDataListener;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.StringUtils;
import cn.com.czpb.client.utils.TUtils;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by 猪猪侠 on 2017/7/6.
 */

public class SeachActivity2 extends ToolBarActivityWhite {
    @BindView(R.id.ll_searchresult_id)
    LinearLayout ll_searchresult_id;
    @BindView(R.id.search_edittext_id)
    EditText search_edittext_id;
    @BindView(R.id.search_clear_ll)//clear button
    LinearLayout search_clear_ll;
    @BindView(R.id.text_search_id)//搜索 按钮
     TextView text_search_id;
    @BindView(R.id.text_remove_id)//取消 按钮
    TextView text_remove_id;
    @BindView(R.id.search_record_lv)
    TagCloudLayout search_record_lv;
    @BindView(R.id.ll_root_id)
    LinearLayout ll_root_id;
    @BindView(R.id.tagclout_layout)
    TagCloudLayout tagclout_layout;
    @BindView(R.id.ll_history_id)
    LinearLayout llHistoryId;
    @BindView(R.id.view_driver_id)
    View viewDriverId;
    @BindView(R.id.tablayout_id)
    TabLayout tablayoutId;
    @BindView(R.id.viewpager_search_id)
    ViewPager viewpagerSearchId;
    private TagHistoryAdapter historyAdapter;
    private TagBaseAdapter hotAdapter;
    private boolean isRefresh = false;
    private int page = 1;
    private static final int pageSize = 15;
    private SearchFragmentPagerAdapter viewpagerAdapter;

    @Override
    public int setMyContentView() {
        return R.layout.search_main_layout;
    }

    @Override
    public void initView() {
        setTitle("搜索");
        initViewPager();

        ll_searchresult_id.setVisibility(View.GONE);
        hotAdapter = new TagBaseAdapter(this);
        tagclout_layout.setAdapter(hotAdapter);
        getHotSearchData();
        final GridLayoutManager gridLayoutManager = new GridLayoutManager(activity, 2);
        gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);


        historyAdapter = new TagHistoryAdapter(this);
        search_record_lv.setAdapter(historyAdapter);


        search_edittext_id.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String ss = s.toString();
                if (ss.length() > 0) {
                    search_clear_ll.setVisibility(View.VISIBLE);
                    text_search_id.setVisibility(View.VISIBLE);
                    text_remove_id.setVisibility(View.GONE);
                    ll_root_id.setVisibility(View.GONE);
                } else if (TextUtils.isEmpty(ss)) {
                    search_clear_ll.setVisibility(View.GONE);
                    text_search_id.setVisibility(View.GONE);
                    text_remove_id.setVisibility(View.VISIBLE);
                    ll_root_id.setVisibility(View.VISIBLE);
                    udaptRecodeListView();
                }
            }
        });
        search_edittext_id.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (inputMethodManager.isActive()) {
                        inputMethodManager.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                    }
                    ll_root_id.setVisibility(View.GONE);
                    reflushListView();
                    return true;

                }
                return false;
            }
        });
        search_edittext_id.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                /*隐藏软键盘*/
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (inputMethodManager.isActive()) {
                        inputMethodManager.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                    }
                    if (!StringUtils.isEmpty(search_edittext_id.getText().toString())) {
                        reflushListView();
                    }
                    return true;
                }
                return false;
            }
        });
        search_record_lv.setItemClickListener(new TagCloudLayout.TagItemClickListener() {
            @Override
            public void itemClick(int position) {
                SearchHisBean bean = historyAdapter.getItem(position);
                String content = bean.getContent();
                search_edittext_id.setText(content);
                ll_root_id.setVisibility(View.GONE);
                reflushListView();
            }
        });
        tagclout_layout.setItemClickListener(new TagCloudLayout.TagItemClickListener() {
            @Override
            public void itemClick(int position) {
                HotSearchBean bean =hotAdapter.getItem(position);
                String content = bean.getContent();
                search_edittext_id.setText(content);
                ll_root_id.setVisibility(View.GONE);
                reflushListView();
            }
        });
        udaptRecodeListView();
    }
    //初始化搜索结果的viewpager
    private void initViewPager() {
        FragmentManager fragmentManager = getSupportFragmentManager();
        List<Fragment> fragmentlist = new ArrayList<>();
        fragmentlist.add(new SearchNewsFragment());
        fragmentlist.add(new SearchSubscribeFragment());
        viewpagerAdapter = new SearchFragmentPagerAdapter(fragmentManager);
        viewpagerAdapter.setFragments(fragmentlist);
        viewpagerSearchId.setAdapter(viewpagerAdapter);

        tablayoutId.setupWithViewPager(viewpagerSearchId);
        viewpagerSearchId.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tablayoutId.getTabAt(position).select();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    @OnClick({R.id.search_ll, R.id.search_clear_tv, R.id.text_remove_id, R.id.text_search_id, R.id.search_clear_ll})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.search_ll:
                String con = search_edittext_id.getText().toString();
                if (null == con || "".equals(con)) {
                    TUtils.toast("请输入内容");
                    return;
                }
                ll_root_id.setVisibility(View.GONE);
                new SearchHisBean(con).save();
                InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(search_edittext_id.getWindowToken(), 0);
                reflushListView();
                break;
            case R.id.search_clear_tv://清楚历史
                llHistoryId.setVisibility(View.GONE);
                LogUtils.i("clear-->"+historyAdapter.getCount());
                DataSupport.deleteAll(SearchHisBean.class);
                historyAdapter.clearData();
                search_record_lv.clearData();

                break;
            case R.id.text_remove_id://取消
                this.finish();
                break;
            case R.id.text_search_id://搜索
                String con2 = search_edittext_id.getText().toString();
                if (null == con2 || "".equals(con2)) {
                    TUtils.toast("请输入内容");
                    return;
                }
                ll_root_id.setVisibility(View.GONE);
                new SearchHisBean(con2).save();
                InputMethodManager inputMethodManager2 = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager2.hideSoftInputFromWindow(search_edittext_id.getWindowToken(), 0);
                reflushListView();
                break;
            case R.id.search_clear_ll:
                LogUtils.i("clear-->");
                search_clear_ll.setVisibility(View.GONE);
                text_remove_id.setVisibility(View.VISIBLE);
                text_search_id.setVisibility(View.GONE);
                search_edittext_id.setText("");
                break;
        }
    }

    private void reflushListView() {
        LogUtils.i("pull--visible");
        RefreshDataListener listener = (RefreshDataListener) viewpagerAdapter.getItem(0);
        RefreshDataListener listener1 = (RefreshDataListener) viewpagerAdapter.getItem(1);
        listener.refreshData(search_edittext_id.getText().toString());
        listener1.refreshData(search_edittext_id.getText().toString());
        ll_searchresult_id.setVisibility(View.VISIBLE);
    }

    private void udaptRecodeListView() {
        final List<SearchHisBean> list = DataSupport.findAll(SearchHisBean.class);
        LogUtils.i("list-->" + list.size());
        if (null != list && list.size() > 0) {
            Collections.reverse(list);
        }
        LogUtils.i("收藏数据--->" + null);
        if (null != list && list.size() > 0) {
            LogUtils.i("收藏数据--->" + list.get(0).getContent());
            ll_root_id.setVisibility(View.VISIBLE);
            llHistoryId.setVisibility(View.VISIBLE);
            viewDriverId.setVisibility(View.VISIBLE);
            ll_searchresult_id.setVisibility(View.GONE);
            historyAdapter.addData(list);
            historyAdapter.notifyDataSetChanged();
        } else {
            llHistoryId.setVisibility(View.GONE);
            viewDriverId.setVisibility(View.GONE);

        }
    }

    //獲取熱門搜索
    private void getHotSearchData() {
        Factory.provideHttpService().newsHotSearch()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<HotSearchEntity, Boolean>() {
                    @Override
                    public Boolean call(HotSearchEntity entity) {
                        LogUtils.i("hotcode-->" + entity.code);
                        return "200".equals(entity.code);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<HotSearchEntity>() {
                    @Override
                    public void call(HotSearchEntity entity) {
                        List<HotSearchBean> mylist = entity.data;
                        LogUtils.i("hotbean-->" + mylist.size());
                        if ("200".equals(entity.code)) {
                            if (null == mylist) {
                                TUtils.toast("暂无数据");
                                return;
                            }
                            List<HotSearchBean> mylist2 = new ArrayList<HotSearchBean>();
                            for (int i = 0; i < 4; i++) {
                                mylist2.add(mylist.get(i));
                            }
                            hotAdapter.addData(mylist2);
                        }

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });


    }


    @Override
    public void initData() {
    }

    private class GridViewAdapter extends BaseAdapter {
        List<HotSearchBean> listhot;
        protected LayoutInflater inflater;

        public GridViewAdapter(Context context) {
            inflater = LayoutInflater.from(context);
            listhot = new ArrayList<>();
        }

        public void setData(List<HotSearchBean> listhot) {
            this.listhot = listhot;
        }

        @Override
        public int getCount() {
            return listhot.size();
        }

        @Override
        public Object getItem(int position) {
            return listhot.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.gride_item, null);
            }
            TextView textView = convertView.findViewById(R.id.gride_item_id);
            textView.setText(listhot.get(position).getContent());
            return convertView;
        }

    }

}
